#include "CField.hpp"
#include "CPlayer.hpp"

#include <stdexcept>
#include <iterator>
#include <iostream>
#include <cassert>

////////////////////////////////////////////////////////////////
// CField
//
/**
* @class CField
*/

/**
* @brief Constructor of CField
*/
CField::CField(uint h, uint w, uint d)
	: width(w)
	, height(h)
	, depth(d)
	, field(new Cell[h * w * d])
{
}

CField::~CField()
{
	delete [] field;
}

/**
* @brief Check mob is not NULL
*/
bool CField::Cell::hasMob()
{
	return pMob != NULL;
}

/*
* @brief Get a cell of the field.
*
* @param pos position as position_t
*
* @return A cell of the field
*/
/*
const CField::cell_t& CField::get(const position_t& pos) const
{
	return this->operator[](pos);
}*/

/**
* @copydoc CField::getCell
*/
CField::Cell& CField::operator[](const position_t& pos) const
{
	assert(pos.x < getWidth());
	assert(pos.y < getHeight());
	assert(pos.z < getDepth());

	return field[
		pos.x * getHeight() * getDepth() +
		pos.y * getDepth() +
		pos.z
	];
}

/**
* @brief Put mob on the field.
*
* @param mob A mob to put.
*/
void CField::putMob(CMob& mob, position_t pos)
{
	Cell& t = operator[](pos);
	mob.pos = pos;
//	assert(t.Mob == NULL);
	t.pMob = &mob;
}

/**
* @brief Remove mob from field
*
* @note This function doesn't delete CMob.
*
* @param pos Position of the mob
*/
void CField::removeMob(position_t pos)
{
	operator[](pos).pMob = NULL;
}

/**
* @brief Print field
*
* @note Num of a cell means how many there is mob
*/
void CField::print() const
{
	std::cout << getWidth() << " x " <<
		getHeight()<< " x " << getDepth() << std::endl;
	std::ostream_iterator<char> oit(std::cout, " ");
	for(uint i = 0; i < getHeight(); i++)
	{
		for(uint j = 0; j < getWidth(); j++)
		{
			int index = (i * getWidth() + j ) * getDepth();
			int bit_mob = 0;
			for(uint h = 0; h < getDepth(); h++)
			{
				if(field[index + h].pMob != NULL)
				{
					//bit_mob |= 1 << h;
					bit_mob++;
				}
			}
		//	*oit = (bit_mob == 0)?'_':bit_mob + '0';
			*oit = bit_mob + '0';
		}
		std::cout << std::endl;
	}
}

